# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
# esp.osdebug(None)
#import webrepl
# webrepl.start()
import utime
from machine import Pin
import network
from simple import MQTTClient

######
WIFI_SID = "sid"
WIFI_PW = "pwd"

SOCKET_TIMEOUT=30

MQ_SERVER_IP = "192.168.199.8"
MQ_SERVER_PORT = "1883"

MQ_SERVER_USER = "admin"
MQ_SERVER_PW = "admin"

CLIENT_ID = "espressif"

SCB_TOPIC = "espressif_rcv"
PUB_TOPIC = "espressif_sed"
######
def on_msg(topic, msg):
    print("topic[%s]msg[%s]" % (topic, msg))


###
try:
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    count = 0
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect(WIFI_SID, WIFI_PW)
        while (not wlan.isconnected()) and count < 10:
            utime.sleep(1)
            count = count+1
        print('network config:', wlan.ifconfig())
    ######
    qc = MQTTClient(CLIENT_ID, MQ_SERVER_IP, MQ_SERVER_PORT,
                    MQ_SERVER_USER, MQ_SERVER_PW)
    qc.timeout=SOCKET_TIMEOUT
    print('mq init.')
    qc.set_callback(on_msg)
    print('mq callback.')
    qc.connect()
    print('mq connect.')
    qc.subscribe(SCB_TOPIC)
    print('mq s.')
    qc.publish(PUB_TOPIC, "hello! from espressif.", retain=True)
    print('mq p.')
    count = 0
    while count < 1:
        qc.wait_msg()
        count=count+1
finally:
    if qc is not None:
        qc.disconnect()
    if wlan is not None:
        wlan.disconnect()
        wlan.active(False)
######
